import {
  EventSubscriber,
  EntitySubscriberInterface,
  InsertEvent,
} from 'typeorm';
import { Login } from '../entity/login.entity';
import { User } from '../entity/user.entity';

@EventSubscriber()
export class UserSubscriber implements EntitySubscriberInterface<User> {
  listenTo() {
    return User;
  }

  // 在插入用户后，插入登录日志
  async afterInsert(event: InsertEvent<User>) {
    const userLog = new Login();
    userLog.userId = event.entity.id;
    userLog.username = event.entity.username;
    userLog.extra = JSON.stringify({});
    try {
      await event.manager.save(userLog);
    } catch (error) {
      console.log(error);
    }
  }
}
